<template>
    <div class="brand-container">
        <el-card shadow="never">
            <el-button
                icon="Plus"
                type="primary"
                size="default"
                @click="addBrand"
                v-permission="`btn.brand.add`"
            >
                添加品牌
            </el-button>
        </el-card>
        <el-card shadow="never">
            <el-table
                border
                highlight-current-row
                stripe
                :data="tableData"
                style="width: 100%"
                type="index"
                max-height="450px"
            >
                <el-table-column label="序号" width="80px" align="center">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="品牌名称" />
                <el-table-column label="品牌Logo">
                    <template #default="{ row }">
                        <el-image
                            lazy
                            style="width: 50px; height: 50px"
                            :src="row.logoUrl"
                            fit="contain"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button
                            icon="Edit"
                            type="warning"
                            @click="updateById(row.id)"
                            v-permission="`btn.brand.update`"
                        >
                            修改
                        </el-button>
                        <el-popconfirm
                            width="200"
                            title="你确定要删除这一项吗?"
                            @confirm="handleDelete(row.id)"
                        >
                            <template #reference>
                                <el-button icon="Delete" type="danger" v-permission="`btn.brand.delete`">
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-pagination
            v-model:current-page="current"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20, 25]"
            small
            layout=" prev, pager, next, jumper,->,sizes, total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
            <el-form ref="actionForm" :model="brandItem" class="dialog-form">
                <el-form-item prop="id"></el-form-item>
                <el-form-item label="品牌名字" prop="name">
                    <el-input v-model="brandItem.name"></el-input>
                </el-form-item>
                <el-form-item label="品牌logo" prop="logoUrl">
                    <el-upload
                        class="avatar-uploader"
                        action="#"
                        ref="upload"
                        :auto-upload="true"
                        :http-request="handleFileUpload"
                        :show-file-list="false"
                    >
                        <img
                            v-if="brandItem.logoUrl"
                            :src="brandItem.logoUrl"
                            class="avatar"
                        />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveOrUpdate">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, toRaw } from 'vue'
import { Brand } from '@/api/product/brand/type.ts'
import {
    reqBrandPage,
    reqBrandQuery,
    reqRemoveBrand,
    reqSaveBrand,
    reqUpdateBrand,
} from '@/api/product/brand'
import { PageInfo } from '@/api/type.ts'
import { ElMessage, FormInstance, UploadRequestOptions } from 'element-plus'
import { reqFileUpload } from '@/api/file'

// 模态框数据
enum TYPE {
    EDIT,
    ADD,
}

let actionForm = ref<FormInstance>()
let dialogVisible = ref(false)
let actionType = ref()
let brandItem = reactive<Brand>({ id: 0, logoUrl: '', name: '' })
const dialogTitle = computed(() => {
    return actionType.value === TYPE.EDIT ? '修改品牌' : '新增品牌'
})
// 删除
const handleDelete = (id: number) => {
    reqRemoveBrand(id)
        .then(() => {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            getBrandPage()
        })
        .catch((err) => {
            ElMessage({
                message: err,
                type: 'error',
            })
            dialogVisible.value = false
        })
}
// 新增或者更新
const handleSaveOrUpdate = () => {
    if (actionType.value === TYPE.ADD) {
        reqSaveBrand(toRaw(brandItem))
            .then(() => {
                ElMessage({
                    message: '新增成功',
                    type: 'success',
                })
                dialogVisible.value = false
                actionForm.value?.resetFields()
                getBrandPage()
            })
            .catch((err) => {
                ElMessage({
                    message: err,
                    type: 'error',
                })
                dialogVisible.value = false
            })
    } else if (actionType.value === TYPE.EDIT) {
        reqUpdateBrand(toRaw(brandItem))
            .then(() => {
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                dialogVisible.value = false
                actionForm.value?.resetFields()
                getBrandPage()
            })
            .catch((err) => {
                ElMessage({
                    message: err,
                    type: 'error',
                })
                dialogVisible.value = false
            })
    }
}
// 上传
const handleFileUpload = (fileObject: UploadRequestOptions) => {
    let fd = new FormData()
    fd.append('file', fileObject.file)
    reqFileUpload(fd)
        .then((res) => {
            brandItem.logoUrl = res.data
        })
        .catch((err) => {
            ElMessage({
                message: err,
                type: 'error',
            })
        })
}
// 修改
const updateById = (id: number) => {
    reqBrandQuery(id).then((res) => {
        brandItem.logoUrl = res.data.logoUrl
        brandItem.name = res.data.name
        brandItem.id = res.data.id
    })
    dialogVisible.value = true
    actionType.value = TYPE.EDIT
}
// 新增
const addBrand = () => {
    dialogVisible.value = true
    actionType.value = TYPE.ADD
}
// 分页数据
let pageInfo = reactive<PageInfo>({
    page: 1,
    limit: 10,
})
const current = ref(1)
const pageSize = ref(10)
const total = ref(0)
let tableData = ref<Brand[]>([])

function getBrandPage() {
    reqBrandPage(pageInfo).then((res) => {
        total.value = res.data.total
        tableData.value = res.data.records
        current.value = res.data.current
    })
}

const handleSizeChange = (val: number) => {
    pageInfo.limit = val
    getBrandPage()
}
const handleCurrentChange = (val: number) => {
    pageInfo.page = val
    getBrandPage()
}
// 数据挂载
onMounted(() => {
    getBrandPage()
})
</script>

<style lang="less" scoped>
.brand-container {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
}
</style>
